use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs;
use std::path::Path;

/// 主配置结构
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Config {
    pub project: ProjectConfig,
    pub translator: TranslatorConfig,
    pub llm: Option<LlmConfig>,
    pub safety_optimizer: SafetyOptimizerConfig,
    pub targets: HashMap<String, TargetConfig>,
}

/// 项目配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProjectConfig {
    pub name: String,
    pub compilation_database: Option<String>,
}

/// 转译器配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TranslatorConfig {
    /// 转译模式: "safe" 或 "unsafe_first"
    pub mode: TranslationMode,
    /// 是否启用并行处理
    pub parallel: bool,
    /// 输出详细信息
    pub verbose: bool,
}

/// 转译模式
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TranslationMode {
    /// 尽可能生成安全代码，可能失败
    Safe,
    /// 先生成可编译的unsafe代码，再优化
    UnsafeFirst,
}

/// LLM配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LlmConfig {
    pub provider: String,
    pub endpoint: String,
    pub model: String,
    pub api_key: Option<String>,
    pub timeout_seconds: u64,
    pub max_tokens: Option<u32>,
    pub temperature: Option<f32>,
}

/// 安全性优化器配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SafetyOptimizerConfig {
    /// 最大迭代次数
    pub max_passes: u32,
    /// 启用的安全提升规则
    pub enabled_linters: Vec<String>,
    /// 是否自动插入SAFETY注释
    pub auto_safety_comments: bool,
}

/// 目标项目配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TargetConfig {
    /// 特殊处理规则
    pub special_handlers: Option<HashMap<String, String>>,
    /// FFI绑定配置
    pub ffi_bindings: Option<Vec<FfiBindingConfig>>,
}

/// FFI绑定配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FfiBindingConfig {
    pub library: String,
    pub mode: String,
    pub wrapper_style: String,
}

impl Default for Config {
    fn default() -> Self {
        Self {
            project: ProjectConfig {
                name: "unnamed_project".to_string(),
                compilation_database: None,
            },
            translator: TranslatorConfig {
                mode: TranslationMode::UnsafeFirst,
                parallel: true,
                verbose: false,
            },
            llm: None,
            safety_optimizer: SafetyOptimizerConfig {
                max_passes: 5,
                enabled_linters: vec![
                    "NonNullPointer".to_string(),
                    "ArrayBoundsCheck".to_string(),
                    "SafeFFIWrapper".to_string(),
                ],
                auto_safety_comments: true,
            },
            targets: HashMap::new(),
        }
    }
}

impl Config {
    /// 从文件加载配置
    pub fn load<P: AsRef<Path>>(path: P) -> Result<Self> {
        let content = fs::read_to_string(&path)
            .with_context(|| format!("无法读取配置文件: {:?}", path.as_ref()))?;
        
        let config: Config = toml::from_str(&content)
            .with_context(|| "配置文件格式错误")?;
        
        Ok(config)
    }
    
}